import { ref } from 'vue';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';

dayjs.extend(duration);

// 计算相隔时间
export function useDurationTime(toTime: string | number | dayjs.Dayjs, fromTime: string | number | dayjs.Dayjs = '') {
    toTime = getDayjsTime(toTime);
    if (fromTime === '') {
        fromTime = dayjs();
    } else {
        fromTime = getDayjsTime(fromTime);
    }

    const duration = ref(toTime.valueOf() - fromTime.valueOf());

    if (duration.value > 0) {
        setTimeout(() => {
            if (duration.value > 0) {
                duration.value -= 1000;
            }
        }, 1000);
    }

    const durationTime = dayjs.duration(duration.value);

    return {
        h: (durationTime.months() * 30 * 24 + durationTime.days() * 24 + durationTime.hours())
            .toString()
            .padStart(2, '0'),
        m: durationTime.minutes().toString().padStart(2, '0'),
        s: durationTime.seconds().toString().padStart(2, '0'),
        ms: durationTime.asMilliseconds(),
    };
}

function getDayjsTime(time: string | number | dayjs.Dayjs): dayjs.Dayjs {
    if (dayjs.isDayjs(time)) return time;
    const strTime = time.toString();
    if (strTime.indexOf('-') > 0) {
        return dayjs(strTime); // date string
    }
    if (strTime.length > 10) {
        return dayjs(parseInt(strTime)); // timestamp
    }
    if (strTime.length === 10) {
        return dayjs.unix(parseInt(strTime)); // unixtime
    }
    return dayjs(); // fallback
}
